package com.cheung.shopkeeper.common.utils;

import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;

//import org.codehaus.jackson.map.ObjectMapper;

public class HttpPostUtil {
	
	public static String doHttpPost(String postUrl, Map<String, String> params) {
		
		HttpClient client = new HttpClient();
		UTF8PostMethod mPost = new UTF8PostMethod(postUrl);
		client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
		client.getHttpConnectionManager().getParams().setSoTimeout(30000);
		String[] keys = params.keySet().toArray(new String[0]);
		for (String key : keys) {
			mPost.addParameter(key, params.get(key));
		}
		String responseTxt = "";
		mPost.getResponseCharSet();
		try {
		    
			int responseCode = client.executeMethod(mPost);
			if (responseCode != HttpStatus.SC_OK) {
				responseTxt = "";
			} else {
				responseTxt = mPost.getResponseBodyAsString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				mPost.releaseConnection();
				client.getHttpConnectionManager().closeIdleConnections(0);
			} catch (Exception e) {
			}
		}
		return responseTxt;
	}
}

class UTF8PostMethod extends PostMethod {
	
	public UTF8PostMethod(String url) {
		super(url);
	}
	
	public String getRequestCharSet() {
		return "UTF-8";
	}
	
	public String getResponseCharSet() {
		return "UTF-8";
	}
}
